package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	Socket client;
	PrintWriter pw;

	public Client() throws UnknownHostException, IOException {
		client = new Socket("127.0.0.1", 7777);
		// pw=new PrintWriter(client.getOutputStream());
		// // BufferedReader br=new BufferedReader(new
		// InputStreamReader(System.in));
		// // pw.write(br.readLine());
		// pw.write("sdfsdfsdfsdfsdf1");
		// pw.close();

		sendMessage(client);
		recieveMessage(client);
		client.close();
	}

	private void sendMessage(Socket client) {
		// 发送消息
		PrintWriter out;
		try {
			out = new PrintWriter(client.getOutputStream(), true);
			out.println("客户端：张三");
			out.println("正文：斯蒂芬\t\n森分");
			out.println("bye");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void recieveMessage(Socket client) {
		try {
			// 收到的消息
			BufferedReader in = new BufferedReader(new InputStreamReader(
					client.getInputStream(), "UTF-8"));
			String line = in.readLine();
			while (line != null && !line.equals("bye")) {
				System.out.println("line:" + line);
				line = in.readLine();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		try {
			new Client();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
